package com.zpz.framework.zpzoauth;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import com.zpz.framework.zpzoauth.common.encrypt.DefaultCrypto;
import com.zpz.framework.zpzoauth.common.encrypt.SignUtil;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthMd5SaltUtil;
import net.sf.json.JSONObject;

/**
 * @author zhangpanzhi
 * @description 生成工具及相关demo
 * @create 2019-10-31 14:47
 */
public class Tools {
    /**
     * 数据加解密KEY
     */
    public static String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJCwQaXeySZ/bBCRL36cqbeGP6QxpIA2dzSlr9CMV28mD+JNwAM8YeIJdjE6U0wURaiZnISkcjPoPVR+tWlQCssyvFPqqplFeQ2HXzQG/WYJ1BXw75r/1IwfSdTUGNeLjrI7/Kt8RjabFlX+a5R99cIiTljd1S8EWcxmHg0qWPpXAgMBAAECgYBclEsNJUY0Geg9mYh4TSnTQlVKbHFDkJYp27JpkMMJXaNgPDuWVnaTOValHRrbXUVNIi0iOk7Qo9NKU2Ekp5CfgCT4DkODFcPsewfL/agQBJKUhJ5aKmDkcs2/PTs0xJNMAP7nPsaDFfAKOk0kH5xA7jj1+Otx+LXTEc5juI4VYQJBAP7HjqsjL8u/3ytkzJ/uK0iRc0odxxl2DhBO9tvz7sIjAynCBY7AIqcTJsPr9v0p762tI/e7rANe9RAzjiP9p1kCQQCRYbER/VMfvoPk9OdA18mUZfnFwOy9+RxML5BPVKYsFibSYRUsCegRo29v4gwFOEoYXKkP8hsP4HtZquxhiikvAkEA0aIZPa9CEH/bfLT/uUgazScAmadOvyBoCfsvG2PmvE5at+0w7XgiCx6y8tog68WptFmWEqyUqGFleuMwvWRkYQJAU8v6c0MP+Zknjv32mXKH10icGnckPi/rNqKnzIIfMgQmpladDIA9SoVowxWJFi0m0DoAnJdRL+qVTs7tZx9qswJBAMP35Ag+8UFJBFzLSqb5ipHaWiNpWaYe2oRqrVbtVu7byjaTp9fgscyOByu+JbJeIaeTi2JCJCdpZoqRe1cAItA=";
    public static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQsEGl3skmf2wQkS9+nKm3hj+kMaSANnc0pa/QjFdvJg/iTcADPGHiCXYxOlNMFEWomZyEpHIz6D1UfrVpUArLMrxT6qqZRXkNh180Bv1mCdQV8O+a/9SMH0nU1BjXi46yO/yrfEY2mxZV/muUffXCIk5Y3dUvBFnMZh4NKlj6VwIDAQAB";

    public static void main(String[] args) throws Exception {
//        客户端请求登录
//        clientRequestLogin();
        System.out.println(ZpzOauthMd5SaltUtil.getPwd("zhy_ksh_wl_pc_xaqts763s9wyz9gtx"));
//		clientid秘钥
        String mingwenmiyao="wsc123456";
        String qianduan=ZpzOauthMd5SaltUtil.getPwd(mingwenmiyao);
        System.out.println("前端："+qianduan);
        String shujku=ZpzOauthMd5SaltUtil.getPwd(qianduan);
        System.out.println("数据库的："+shujku);

//        解密
        String deData1= de("IHlHwI6xde5S3wP54ev6XUSMcNYlpLw9/KM5umrX9nmCRo2N5luxrPgD5xqsJHe0Oc/ZCUraRvNMmfZw5f51xtRtjGv3YneR9ZMFjRU073QcxCMRL2z9cczkbKsdW0dGgvVzxP6KVLdxiJy96RDKRI8k/uwHT7odEV3jDnGJ19CHsMR+M0H4FCjVmNLoOg5vkL/rpKepsBSU2F0wqyf2dDBwxAWCO2rEBKy+UbBdtdmYXgL9ED0DoiCSa2HogiXXRR3TEH7Bz/Kgg4O18JssOXbqP63TfVYe5AuLpGTVvcOAHGY6IZuYRQxkDXUaaGDMTw7NRLrkGv3R3Y0PrxCyFEMZS+HoC9sAqVaNGvyymWYB/0j25E+6HtDFDPYXYNZ4f3wDrENc8rENSN7cCQ8KrJoU2imjyyhhxfNOXILCAS5Hc0EE0OfV78rq2lWC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gTduAI5qrd11WyGTQWyJZX50vOH1I9OXU5XtP3tVYFNdcZkx3GbN2uG+HL0+pZZdYOp2OwmG9Jfp4bb6sXIBvyA9ApN/5H2PeAVB6HgO8ahIbObqKs0SMrH6GdbX0E+2VlnOOFcxov+kbEYc3OsucTIFh0gqyD6zLxszIkSiq97zQ50oldnR/wqyjLsiWh5Rqeo01S/JQIarH6cboZQplBHinShn5SZuPKRduOLjWtasnhdmwzlK81CZ5GPM8GpKkf2euvfgEJCLOHqbMuppLzG4pCJOVyeUc9D9sV9Y7Jee+B/ggy04khdaaGsW0/VngfjXh+9skLiWovTslgMiG8qFb2h8/xAfKJF/L7vbXe9cpOaNCH66c1LPvOkkh6YG6YNCyaCk0Z11k0d06Wjfim0fifasKSc1exOEB5RrfeK+XnmXxXpZbcLP6EDbb1UXe4pmeZylJZCJgA8QRLNngK0d1J");
        System.out.println("解密数据1："+deData1);

//        String deData2= de("bK1pO59BLG1Ls4lMHenCY7pJEBOMEln2fYau3QkuGWMxd520y5i6+FBPrMHSliaxCOLQnZY8Wvl9GAys6D4yL0o6Jb4vUBQaHdyu0dlp43ZRyhQgCTEAcCCOtZrbXTA+AuKliFUgj6CeciFyz50XylZvxcEAJ6T2GvrXgZsVVyop8rYAJ1TG11ptvsAUnloSAcSk+zvZmBlb31tiQ/OLu26wONWYLakVN6OXa2VPRDboAj8PfuZ2SNXchBLh30sfPepVDcJnV2ELqORzPZpX4PbpifL4ZYM5jAAfDKaQ8SFtKSqgXopZRfEdPT295c3gh2uFPtsJ0RvTTUvqn25r1l7/lPEdUCdtaaGoPko/zdtdJExh2u7g2GV1ukoCqMhEyHtydQbn3GutEjOVj1u/PjPGioJkY7d+QswIyW4XzeN4KLcb48+xBYZ7xeHWBaeMEl4N2b59lziKjURXq/QhXXllNQzc/Db70Cy8Oun9PiG+kp/FYx3KQ0YBRu1Ok9yIbcKOYW7F6mInyZ8zLH911vgQ06mohG0fUxSA1wSeK5tigYWcc/b+0r0OXPn1k7IDTmSg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QF8XwzknebPgD34tdOepJOJ3U2FdXMfxJRwWv3cvT2ruImOrENmtOaF7/Pa5weQbPd/0Ev+prUOs+kr7/VN9sA9dkscdRoe0PJojhUnS9O8QmTakVrNiYr/cJ9yI7O8APqjrAov9Yj6JLgmzJ+AWR5DwHmXTm034cgAg8ISAXY7oIidc0hLmNEpEONsd2H2Xx55PuRBGP+3CCsJrwLVvNewUPpCJKCtgzGzjmteWE/mw4QZuEzOWQoIHeLIBw3lcNHzqawSjZFKkhmLyjMfjZ0YUw7r22yF2XsjP+VcnlRCXUjMIDIVxUKZkjljksMJ8l52Ko3OdW1P6DKMR4pJqrRIK5pmaRHKVGJGAxVVpvCrU3g+LLVudZmkF6xWbXk8tPDZnrVKZRkciI0QOb/XpyvQTMZdU+9MidMIJf0Fo5U+HdQcD0lDl5VhVTLtTJi2Hw97L5y4m6pi6jFVXD2jLWmjcmdAdQeKgx+4u+GQc=");
//        System.out.println("解密数据2："+deData2);

        //扫码加气-下单接口
//		Map<String, Object> map=new HashMap<>();
//		map.put("billEndTime", "2019-06-30 23:59:59");
//		map.put("billStartTime", "2019-06-01 00:00:00");
//		map.put("billType", 3);
//		map.put("billTypeVal", "6");
//		map.put("billYear", "2019");
//		map.put("gasStationId", 20);
//		jiami(map,"auyan_gasstation", "600007", "d6035a39253245a8971aee134891c43f");

    }

    public static void jiami(Object obj,String clientId,String apicode,String userCode){
        String license= clientId+":"+apicode+":"+userCode;
        String data= com.alibaba.fastjson.JSONObject.toJSONString(obj);
        //加密数据
        Map<String, String> en = en(data);
        System.out.println(com.alibaba.fastjson.JSONObject.toJSON(en));
        base64Method(license);
        //解密数据
//		TestSecurity.de(enStr);
    }
    public static void base64Method(String str){
        final Base64.Decoder decoder = Base64.getDecoder();
        final Base64.Encoder encoder = Base64.getEncoder();
        byte[] textByte;
        try {
            textByte = str.getBytes("UTF-8");
            //编码
            final String encodedText = encoder.encodeToString(textByte);
            System.out.println("license:"+encodedText);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> en(String data) {
        try {
            data = DefaultCrypto.encodDataPublicKey(data, PUBLIC_KEY);
            String signKey = "414c92090b5f05cf372101c3426adfa2";
            //签名
            String nonceStr = SignUtil.generateNonceStr();
            System.out.println("随机字符串：" + nonceStr);
            String sign = SignUtil.MD5(data + nonceStr + signKey);
            System.out.println("签名：" + sign);
            Map<String, String> map = new HashMap<>();
            map.put("sign", sign);
            map.put("nonceStr", nonceStr);
            map.put("data", data);
            return map;
            /************************************************/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String de(String enStr) {
        try {
            String s1 = DefaultCrypto.decodDataPrivateKey(enStr, PRIVATE_KEY);
            return s1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean checkSign(String enStr, String nonceStr, String sign) {
        try {
            String signKey = "414c92090b5f05cf372101c3426adfa2";
            boolean signatureValid = SignUtil.MD5(enStr + nonceStr + signKey).toUpperCase().equals(sign.toUpperCase());
            return signatureValid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
    * 客户端请求登录（如不动产自助机）
    * */
    public static void clientRequestLogin() throws Exception{
        JSONObject json = new JSONObject();
        json.put("grant_type", "pscopeassword");
        json.put("password", "123456");
        json.put("username", "18668979240");
        json.put("scope", "all");
        json.put("auth_type", "mobile_pwd");

        String url = "http://localhost:5020/api/oauth/token";

        String str = Tools.post(url, json.toString());

        System.out.println(str);

    }

    /*
    * POST请求方法
    * */
    public static String post(String postUrl, String postData) throws Exception {
        String line, result = "";
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");

        String base64 = "";
        conn.setRequestProperty("Authorization", "Basic bGZfYmRjX3Rha29ub206YWZkODcxOTcxNjRhYjJlZDliOTY4NmM4MWIwMWU5MzA=");
        conn.setRequestProperty("license", "bGZfYmRjX3Rha29ub206MTAwMDAwOmFueW9uZQ==");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    }
}
